


package jnpf.zc.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.GeneraterSwapUtil;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import jnpf.zc.entity.ZcglCustomerBusinessEntity;
import jnpf.zc.entity.ZcglCustomerEntity;
import jnpf.zc.entity.ZcglCustomerUserEntity;
import jnpf.zc.model.zcglcustomer.*;
import jnpf.zc.service.ZcglCustomerBusinessService;
import jnpf.zc.service.ZcglCustomerService;
import jnpf.zc.service.ZcglCustomerUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;


/**
 * 客户库
 *
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-12-28
 */
@Slf4j
@RestController
@Api(tags = "客户库", value = "example")
@RequestMapping("/api/example/ZcglCustomer")
public class ZcglCustomerController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;


    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcglCustomerService zcglCustomerService;


    @Autowired
    private ZcglCustomerBusinessService zcglCustomerBusinessService;
    @Autowired
    private ZcglCustomerUserService zcglCustomerUserService;

    /**
     * 列表
     *
     * @param zcglCustomerPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZcglCustomerPagination zcglCustomerPagination) throws IOException {
        List<ZcglCustomerEntity> list = zcglCustomerService.getList(zcglCustomerPagination);
        //处理id字段转名称，若无需转或者为空可删除

        List<ZcglCustomerListVO> listVO = JsonUtil.getJsonToList(list, ZcglCustomerListVO.class);
        for (ZcglCustomerListVO zcglCustomerVO : listVO) {
            zcglCustomerVO.setCustomerName_name(zcglCustomerVO.getCustomerName());

            zcglCustomerVO.setProject_name(generaterSwapUtil.getDicName(zcglCustomerVO.getProject(), "600000000000000005"));

            zcglCustomerVO.setCustomerSource_name(generaterSwapUtil.getDicName(zcglCustomerVO.getCustomerSource(), "600000000000000004"));

            zcglCustomerVO.setCustomerType_name(zcglCustomerVO.getCustomerType());

            zcglCustomerVO.setCustomerNature_name(zcglCustomerVO.getCustomerNature());

            zcglCustomerVO.setCustomersIndustry_name(zcglCustomerVO.getCustomersIndustry());

            zcglCustomerVO.setCustomerCreditCode_name(zcglCustomerVO.getCustomerCreditCode());

            zcglCustomerVO.setDetailedAddress_name(zcglCustomerVO.getDetailedAddress());

            zcglCustomerVO.setNotes_name(zcglCustomerVO.getNotes());

            ZcglCustomerBusinessEntity zcglCustomerBusinessEntity = zcglCustomerService.getZcglCustomerBusiness(zcglCustomerVO.getId());
            if (ObjectUtil.isNotEmpty(zcglCustomerBusinessEntity)) {
                ZcglCustomerBusinessListVO zcglCustomerBusinessListVO = JsonUtil.getJsonToBean(zcglCustomerBusinessEntity, ZcglCustomerBusinessListVO.class);
                zcglCustomerBusinessListVO.setLegalRepresentative_name(zcglCustomerBusinessListVO.getLegalRepresentative());

                zcglCustomerBusinessListVO.setRegisteredCapital_name(zcglCustomerBusinessListVO.getRegisteredCapital());

                zcglCustomerBusinessListVO.setEstablishmentDate_name(zcglCustomerBusinessListVO.getEstablishmentDate());

                zcglCustomerBusinessListVO.setBusinessStatus_name(zcglCustomerBusinessListVO.getBusinessStatus());

                zcglCustomerBusinessListVO.setBusinessRegistrationNumber_name(zcglCustomerBusinessListVO.getBusinessRegistrationNumber());

                zcglCustomerBusinessListVO.setCreditCode_name(zcglCustomerBusinessListVO.getCreditCode());

                zcglCustomerBusinessListVO.setOrganizationCode_name(zcglCustomerBusinessListVO.getOrganizationCode());

                zcglCustomerBusinessListVO.setTaxpayerNumber_name(zcglCustomerBusinessListVO.getTaxpayerNumber());

                zcglCustomerBusinessListVO.setEnterpriseType_name(zcglCustomerBusinessListVO.getEnterpriseType());

                zcglCustomerBusinessListVO.setStartTime_name(zcglCustomerBusinessListVO.getStartTime());

                zcglCustomerBusinessListVO.setEndTime_name(zcglCustomerBusinessListVO.getEndTime());

                zcglCustomerBusinessListVO.setIndustry_name(zcglCustomerBusinessListVO.getIndustry());

                zcglCustomerBusinessListVO.setApprovalDate_name(zcglCustomerBusinessListVO.getApprovalDate());

                zcglCustomerBusinessListVO.setPaidCapital_name(zcglCustomerBusinessListVO.getPaidCapital());

                zcglCustomerBusinessListVO.setStafsize_name(zcglCustomerBusinessListVO.getStafsize());

                zcglCustomerBusinessListVO.setIndividualsNumber_name(zcglCustomerBusinessListVO.getIndividualsNumber());

                zcglCustomerBusinessListVO.setRegistrationAuthority_name(zcglCustomerBusinessListVO.getRegistrationAuthority());

                zcglCustomerBusinessListVO.setFormerName_name(zcglCustomerBusinessListVO.getFormerName());

                zcglCustomerBusinessListVO.setEnglishName_name(zcglCustomerBusinessListVO.getEnglishName());

                zcglCustomerBusinessListVO.setRegisteredAddress_name(zcglCustomerBusinessListVO.getRegisteredAddress());

                zcglCustomerBusinessListVO.setBusinessScope_name(zcglCustomerBusinessListVO.getBusinessScope());

                zcglCustomerVO.setZcgl_customer_business(zcglCustomerBusinessListVO);
            }
            ZcglCustomerUserEntity zcglCustomerUserEntity = zcglCustomerService.getZcglCustomerUser(zcglCustomerVO.getId());
            if (ObjectUtil.isNotEmpty(zcglCustomerUserEntity)) {
                ZcglCustomerUserListVO zcglCustomerUserListVO = JsonUtil.getJsonToBean(zcglCustomerUserEntity, ZcglCustomerUserListVO.class);
                zcglCustomerUserListVO.setContacts_name(zcglCustomerUserListVO.getContacts());

                zcglCustomerUserListVO.setContactNumber_name(zcglCustomerUserListVO.getContactNumber());

                zcglCustomerUserListVO.setEmail_name(zcglCustomerUserListVO.getEmail());

                zcglCustomerUserListVO.setPosition_name(zcglCustomerUserListVO.getPosition());

                zcglCustomerVO.setZcgl_customer_user(zcglCustomerUserListVO);
            }
            //子表数据转换
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zcglCustomerPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    @ApiOperation("获取客户下拉列表")
    @PostMapping("/getAllList")
    public ActionResult getAllList(){
        List<ZcglCustomerEntity> list = zcglCustomerService.list();
        return ActionResult.success(list);
    }

    /**
     * 创建
     *
     * @param zcglCustomerForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcglCustomerForm zcglCustomerForm) throws DataException {
        boolean b = zcglCustomerService.checkForm(zcglCustomerForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcglCustomerEntity entity = JsonUtil.getJsonToBean(zcglCustomerForm, ZcglCustomerEntity.class);
        entity.setId(mainId);
        zcglCustomerService.save(entity);

        //子表数据
        if (ObjectUtil.isNotEmpty(zcglCustomerForm.getZcgl_customer_business())) {
            ZcglCustomerBusinessEntity zcgl_customer_businessentity = JsonUtil.getJsonToBean(zcglCustomerForm.getZcgl_customer_business(), ZcglCustomerBusinessEntity.class);

            //自动生成的字段
            zcgl_customer_businessentity.setParentid(entity.getId());
            zcgl_customer_businessentity.setId(mainId);
            zcglCustomerBusinessService.save(zcgl_customer_businessentity);
        }
        if (ObjectUtil.isNotEmpty(zcglCustomerForm.getZcgl_customer_user())) {
            ZcglCustomerUserEntity zcgl_customer_userentity = JsonUtil.getJsonToBean(zcglCustomerForm.getZcgl_customer_user(), ZcglCustomerUserEntity.class);

            //自动生成的字段
            zcgl_customer_userentity.setParentid(entity.getId());
            zcgl_customer_userentity.setId(mainId);
            zcglCustomerUserService.save(zcgl_customer_userentity);
        }

        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcglCustomerInfoVO> info(@PathVariable("id") String id) {
        ZcglCustomerEntity entity = zcglCustomerService.getInfo(id);
        ZcglCustomerInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCustomerInfoVO.class);

        //子表
        //副表
        QueryWrapper<ZcglCustomerBusinessEntity> queryWrapperZcglCustomerBusiness = new QueryWrapper<>();
        queryWrapperZcglCustomerBusiness.lambda().eq(ZcglCustomerBusinessEntity::getParentid, entity.getId());
        ZcglCustomerBusinessEntity zcgl_customer_businessEntity = zcglCustomerBusinessService.getOne(queryWrapperZcglCustomerBusiness);
        ZcglCustomerBusinessModel zcglCustomerBusinessModel = JsonUtil.getJsonToBean(zcgl_customer_businessEntity, ZcglCustomerBusinessModel.class);
        vo.setZcgl_customer_business(zcglCustomerBusinessModel);
        QueryWrapper<ZcglCustomerUserEntity> queryWrapperZcglCustomerUser = new QueryWrapper<>();
        queryWrapperZcglCustomerUser.lambda().eq(ZcglCustomerUserEntity::getParentid, entity.getId());
        ZcglCustomerUserEntity zcgl_customer_userEntity = zcglCustomerUserService.getOne(queryWrapperZcglCustomerUser);
        ZcglCustomerUserModel zcglCustomerUserModel = JsonUtil.getJsonToBean(zcgl_customer_userEntity, ZcglCustomerUserModel.class);
        vo.setZcgl_customer_user(zcglCustomerUserModel);
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcglCustomerInfoVO> detailInfo(@PathVariable("id") String id) {
        ZcglCustomerEntity entity = zcglCustomerService.getInfo(id);
        ZcglCustomerInfoVO vo = JsonUtil.getJsonToBean(entity, ZcglCustomerInfoVO.class);

        //子表数据转换

        //附表数据转换
        QueryWrapper<ZcglCustomerBusinessEntity> queryWrapperZcglCustomerBusiness = new QueryWrapper<>();
        queryWrapperZcglCustomerBusiness.lambda().eq(ZcglCustomerBusinessEntity::getParentid, entity.getId());
        ZcglCustomerBusinessEntity zcgl_customer_businessEntity = zcglCustomerBusinessService.getOne(queryWrapperZcglCustomerBusiness);
        if (ObjectUtil.isEmpty(zcgl_customer_businessEntity)) {
            zcgl_customer_businessEntity = new ZcglCustomerBusinessEntity();
        }
        zcgl_customer_businessEntity.setLegalRepresentative(zcgl_customer_businessEntity.getLegalRepresentative());

        zcgl_customer_businessEntity.setRegisteredCapital(zcgl_customer_businessEntity.getRegisteredCapital());

        zcgl_customer_businessEntity.setEstablishmentDate(zcgl_customer_businessEntity.getEstablishmentDate());

        zcgl_customer_businessEntity.setBusinessStatus(zcgl_customer_businessEntity.getBusinessStatus());

        zcgl_customer_businessEntity.setBusinessRegistrationNumber(zcgl_customer_businessEntity.getBusinessRegistrationNumber());

        zcgl_customer_businessEntity.setCreditCode(zcgl_customer_businessEntity.getCreditCode());

        zcgl_customer_businessEntity.setOrganizationCode(zcgl_customer_businessEntity.getOrganizationCode());

        zcgl_customer_businessEntity.setTaxpayerNumber(zcgl_customer_businessEntity.getTaxpayerNumber());

        zcgl_customer_businessEntity.setEnterpriseType(zcgl_customer_businessEntity.getEnterpriseType());

        zcgl_customer_businessEntity.setStartTime(zcgl_customer_businessEntity.getStartTime());

        zcgl_customer_businessEntity.setEndTime(zcgl_customer_businessEntity.getEndTime());

        zcgl_customer_businessEntity.setIndustry(zcgl_customer_businessEntity.getIndustry());

        zcgl_customer_businessEntity.setApprovalDate(zcgl_customer_businessEntity.getApprovalDate());

        zcgl_customer_businessEntity.setPaidCapital(zcgl_customer_businessEntity.getPaidCapital());

        zcgl_customer_businessEntity.setStafsize(zcgl_customer_businessEntity.getStafsize());

        zcgl_customer_businessEntity.setIndividualsNumber(zcgl_customer_businessEntity.getIndividualsNumber());

        zcgl_customer_businessEntity.setRegistrationAuthority(zcgl_customer_businessEntity.getRegistrationAuthority());

        zcgl_customer_businessEntity.setFormerName(zcgl_customer_businessEntity.getFormerName());

        zcgl_customer_businessEntity.setEnglishName(zcgl_customer_businessEntity.getEnglishName());

        zcgl_customer_businessEntity.setRegisteredAddress(zcgl_customer_businessEntity.getRegisteredAddress());

        zcgl_customer_businessEntity.setBusinessScope(zcgl_customer_businessEntity.getBusinessScope());

        ZcglCustomerBusinessModel zcglCustomerBusinessModel = JsonUtil.getJsonToBean(zcgl_customer_businessEntity, ZcglCustomerBusinessModel.class);
        vo.setZcgl_customer_business(zcglCustomerBusinessModel);
        QueryWrapper<ZcglCustomerUserEntity> queryWrapperZcglCustomerUser = new QueryWrapper<>();
        queryWrapperZcglCustomerUser.lambda().eq(ZcglCustomerUserEntity::getParentid, entity.getId());
        ZcglCustomerUserEntity zcgl_customer_userEntity = zcglCustomerUserService.getOne(queryWrapperZcglCustomerUser);
        if (ObjectUtil.isEmpty(zcgl_customer_userEntity)) {
            zcgl_customer_userEntity = new ZcglCustomerUserEntity();
        }
        zcgl_customer_userEntity.setContacts(zcgl_customer_userEntity.getContacts());

        zcgl_customer_userEntity.setContactNumber(zcgl_customer_userEntity.getContactNumber());

        zcgl_customer_userEntity.setEmail(zcgl_customer_userEntity.getEmail());

        zcgl_customer_userEntity.setPosition(zcgl_customer_userEntity.getPosition());

        ZcglCustomerUserModel zcglCustomerUserModel = JsonUtil.getJsonToBean(zcgl_customer_userEntity, ZcglCustomerUserModel.class);
        vo.setZcgl_customer_user(zcglCustomerUserModel);

//添加到详情表单对象中
        vo.setCustomerName(vo.getCustomerName());

        vo.setProject(generaterSwapUtil.getDicName(vo.getProject(), "600000000000000005"));

        vo.setCustomerSource(generaterSwapUtil.getDicName(vo.getCustomerSource(), "600000000000000004"));

        vo.setCustomerType(vo.getCustomerType());

        vo.setCustomerNature(vo.getCustomerNature());

        vo.setCustomersIndustry(vo.getCustomersIndustry());

        vo.setCustomerCreditCode(vo.getCustomerCreditCode());

        vo.setDetailedAddress(vo.getDetailedAddress());

        vo.setNotes(vo.getNotes());


        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param zcglCustomerForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZcglCustomerForm zcglCustomerForm) throws DataException {
        boolean b = zcglCustomerService.checkForm(zcglCustomerForm, 1);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo = userProvider.get();
        ZcglCustomerEntity entity = zcglCustomerService.getInfo(id);
        if (entity != null) {
            ZcglCustomerEntity subentity = JsonUtil.getJsonToBean(zcglCustomerForm, ZcglCustomerEntity.class);
            boolean b1 = zcglCustomerService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }
            //子表数据
            if (ObjectUtil.isNotEmpty(zcglCustomerForm.getZcgl_customer_business())) {
                QueryWrapper<ZcglCustomerBusinessEntity> queryWrapperZcglCustomerBusiness = new QueryWrapper<>();
                queryWrapperZcglCustomerBusiness.lambda().eq(ZcglCustomerBusinessEntity::getParentid, entity.getId());
                ZcglCustomerBusinessEntity zcgl_customer_businessOneEntity = zcglCustomerBusinessService.getOne(queryWrapperZcglCustomerBusiness);
                ZcglCustomerBusinessEntity zcgl_customer_businessentity = JsonUtil.getJsonToBean(zcglCustomerForm.getZcgl_customer_business(), ZcglCustomerBusinessEntity.class);
                zcgl_customer_businessentity.setId(zcgl_customer_businessOneEntity.getId());
                zcgl_customer_businessentity.setParentid(entity.getId());
                zcglCustomerBusinessService.updateById(zcgl_customer_businessentity);
            }
            if (ObjectUtil.isNotEmpty(zcglCustomerForm.getZcgl_customer_user())) {
                QueryWrapper<ZcglCustomerUserEntity> queryWrapperZcglCustomerUser = new QueryWrapper<>();
                queryWrapperZcglCustomerUser.lambda().eq(ZcglCustomerUserEntity::getParentid, entity.getId());
                ZcglCustomerUserEntity zcgl_customer_userOneEntity = zcglCustomerUserService.getOne(queryWrapperZcglCustomerUser);
                ZcglCustomerUserEntity zcgl_customer_userentity = JsonUtil.getJsonToBean(zcglCustomerForm.getZcgl_customer_user(), ZcglCustomerUserEntity.class);
                zcgl_customer_userentity.setId(zcgl_customer_userOneEntity.getId());
                zcgl_customer_userentity.setParentid(entity.getId());
                zcglCustomerUserService.updateById(zcgl_customer_userentity);
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZcglCustomerEntity entity = zcglCustomerService.getInfo(id);
        if (entity != null) {
            zcglCustomerService.delete(entity);
            //子表数据
            QueryWrapper<ZcglCustomerBusinessEntity> queryWrapperZcglCustomerBusiness = new QueryWrapper<>();
            queryWrapperZcglCustomerBusiness.lambda().eq(ZcglCustomerBusinessEntity::getParentid, entity.getId());
            zcglCustomerBusinessService.remove(queryWrapperZcglCustomerBusiness);
            QueryWrapper<ZcglCustomerUserEntity> queryWrapperZcglCustomerUser = new QueryWrapper<>();
            queryWrapperZcglCustomerUser.lambda().eq(ZcglCustomerUserEntity::getParentid, entity.getId());
            zcglCustomerUserService.remove(queryWrapperZcglCustomerUser);

        }
        return ActionResult.success("删除成功");
    }


}
